package modbus

import (
	"dcs/db"
	"dcs/model"
	"fmt"
	"strings"
	"time"
)

// SyncMachineStatus 读取机台状态，合并纱锭状态， 存入数据库
func (c *Client) SyncMachineStatus(machine *model.Base_machine, spindleStatus string) *model.Log_machine_status {

	req := MakeReadMachineStatusRequest()
	c.Conn.Write(req)

	buf := make([]byte, 1024)
	n, err := c.Conn.Read(buf)
	if err != nil {
		fmt.Println("read err:", err)
		return nil
	}
	fmt.Println(string(buf[0:n]))

	var raw_machine_statu = model.Raw_machine_status{}
	var raw_data []byte = Modbus_decode(buf, n)

	current := time.Now().Format("2006-01-02 15:04:05")
	addr := c.Conn.RemoteAddr().String()
	ip := strings.Split(addr, ":")[0]
	raw_machine_statu.Machine_ip = ip
	raw_machine_statu.Dtime = current
	raw_machine_statu.Raw_data = raw_data

	db.GormDb.Create(&raw_machine_statu)

	log_machine_statu := raw_machine_statu.Interpret()
	log_machine_statu.Dtime = current
	//cache := machine.DumpCache()
	//log_machine_statu.Spindles = cache
	log_machine_statu.Spindles = spindleStatus

	db.GormDb.Create(log_machine_statu)

	return log_machine_statu
}
